package com.chenfan.mcn.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chenfan.common.exception.BusinessException;
import com.chenfan.mcn.enums.OperateLockEnum;
import com.chenfan.mcn.exception.McnErrorCode;
import com.chenfan.mcn.extension.Res;
import com.chenfan.mcn.extension.excel.ExcelUtils;
import com.chenfan.common.extension.validation.groups.Add;
import com.chenfan.common.extension.validation.groups.Modify;
import com.chenfan.common.extension.lock.DistributedLockTemplate;
import com.chenfan.mcn.model.dto.*;
import com.chenfan.mcn.model.vo.LiveCommodityListVO;
import com.chenfan.mcn.utils.BusinessAssert;
import com.chenfan.privilege.common.config.SearchAuthority;
import com.chenfan.privilege.common.config.UrlAuth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.chenfan.mcn.service.LiveCommodityService;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 直播商品管理
 * @author wulg
 * @date 2023/3/13
 */
@Slf4j
@RestController
@RequestMapping("/liveCommodity")
public class LiveCommodityController {

    @Autowired
    private LiveCommodityService liveCommodityService;


    /**
     * 新增
     * @param saveDTO
     * @return
     */
    @PostMapping("/add")
    public Res<Long> add(@Validated(Add.class) @RequestBody LiveCommodityInfoSaveDTO saveDTO) {
        return Res.ok(liveCommodityService.save(saveDTO));
    }

    /**
     * 编辑
     * @param saveDTO
     * @return
     */
    @PostMapping("/modify")
    public Res<Long> update(@Validated(Modify.class) @RequestBody LiveCommodityInfoSaveDTO saveDTO) {
        return Res.ok(DistributedLockTemplate.execute(OperateLockEnum.LIVE_CONTRACT_COMMODITY.generateKey(saveDTO.getId()),
                () -> liveCommodityService.save(saveDTO)));
    }

    /**
     * 变更商品状态
     * @param dto
     * @return
     */
    @PostMapping("/changeCommodityStatus")
    public Res<Boolean> changeCommodityStatus(@Validated @RequestBody LiveCommodityStatusDTO dto) {
        return Res.ok(liveCommodityService.changeCommodityStatus(dto));
    }

    /**
     * 列表分页查询
     * @param searchDTO
     * @return
     */
    @PostMapping("/page")
    public Res<Page<LiveCommodityListVO>> page(@SearchAuthority(filterCustomer = false) LiveCommoditySearchDTO searchDTO) {
        return Res.ok(liveCommodityService.page(searchDTO));
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public Res<LiveCommodityListVO> detail(@RequestParam Long id) {
        return Res.ok(liveCommodityService.detail(id));
    }


    /**
     * 导出
     * @param searchDTO
     * @param response
     */
    @PostMapping("/exportExcel")
    @UrlAuth({"liveScheduling_exportdc"})
    public void exportExcel(@SearchAuthority(filterCustomer = false) LiveCommoditySearchDTO searchDTO, HttpServletResponse response) {
        Map<String, Object> map = liveCommodityService.exportExcel(searchDTO);
        StringBuilder filename = new StringBuilder((String) map.get("title")).append("_").append(map.get("live_date")).append(".xlsx");
        ExcelUtils.exportExcel((List<LiveCommodityListVO>) map.get("dataList"), filename.toString(), LiveCommodityListVO.class, filename.toString(), response);
    }


    /**
     * 导入商品
     * @param multipartFile
     * @return
     */
    @PostMapping("/importCommodity")
    @UrlAuth({"liveScheduling_exportdr"})
    public Res<String> importCommodity(@RequestParam("multipartFile") MultipartFile multipartFile,
                                       @RequestParam Long id) {
        List<CommodityInputDTO> inputList = ExcelUtils.importExcel(multipartFile, CommodityInputDTO.class);
        BusinessAssert.notEmpty(inputList, McnErrorCode.IMPORT_CONTENT_EMPTY);
        return Res.ok(liveCommodityService.importCommodity(inputList, id));
    }

    /**
     * 导入商品
     * @param multipartFile
     * @return
     */
    @PostMapping("/importSettlmentCommodity")
    @UrlAuth({"liveProductManagement_settlmentImport"})
    public Res<String> importSettlmentCommodity(@RequestParam MultipartFile multipartFile) {
        List<SettlementCommodityInputDTO> inputList = null;
        try {
            inputList = ExcelUtils.importBigExcel(multipartFile, SettlementCommodityInputDTO.class);
        } catch (Exception e) {
            throw new BusinessException(McnErrorCode.IMPORT_EXCEL_FAILED);
        }
        BusinessAssert.notEmpty(inputList, McnErrorCode.IMPORT_CONTENT_EMPTY);
        try {
            return Res.ok(liveCommodityService.importSettlmentCommodity(inputList));
        } finally {
            inputList.clear();
        }
    }

    /**
     * 下载失败原因
     * @param response
     * @param type 1:导入商品 2：导入结算商品
     * @param fileId 失败文件ID
     */
    @Deprecated
    @GetMapping("/download/failReason")
    public void downloadFailedReason(HttpServletResponse response, String fileId, @RequestParam(defaultValue = "1") Integer type) {
        log.info("收到下载导入失败原因文件请求，fileId={}，type={}", fileId,type);
        liveCommodityService.downloadFailedReason(response, fileId, type);
    }

    /**
     * （批量）有无合同认领
     * @param dto
     * @return
     */
    @PostMapping("/claim")
    @UrlAuth({"liveProductManagement_noContract"})
    public Res<Boolean> claim(@Validated @RequestBody LiveCommodityClaimDTO dto) {
        return Res.ok(liveCommodityService.claim(dto));
    }

    /**
     * 删除直播商品
     *
     * @param dto
     * @return
     */
    @PostMapping("/delete")
    @UrlAuth({"liveScheduling_delete"})
    public Res<Boolean> delete(@RequestBody LiveCommodityClaimDTO dto) {
        liveCommodityService.delete(dto);
        return Res.ok(true);
    }
}
